/*
 * jxSwing Project (2014)
 * 
 * by Denilson Edinaldo Pinto
 * 
 * LGPL
 * Copyright (C) 2014
 * 
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU Lesser General Public License for more details.
 * 
 * You should have received a copy of the GNU Lesser General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
package org.jxSwing.component.button;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.io.IOException;

import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.jxSwing.component.chooser.FileChooser;
import org.jxSwing.i18n.I18N;

/**
 * @author Denilson Edinaldo Pinto
 * @porject jxSwing
 * @package org.jxSwing.component.button
 * @date 20/03/2014 - 20:40:22
 */
public abstract class OpenFileButton extends OpenButton {
	
	private static final long serialVersionUID = 7919754311290913124L;
	
	private FileNameExtensionFilter filter = null;
	
	private JComponent component = null;
	
	/**
	 * @param component
	 * @param filter
	 */
	public OpenFileButton(final JComponent component, final FileNameExtensionFilter filter) {
	
		this.component = component;
		this.filter = filter;
		
		initGUI();
	}
	
	/**
	 * 
	 */
	private void initGUI() {
	
		setToolTipText(I18N.component().openFile());
		
		addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(final ActionEvent actionEvent) {
			
				//
				new Thread(new Runnable() {
					
					@Override
					public void run() {
					
						final FileChooser chooser = new FileChooser();
						
						chooser.setMultiSelectionEnabled(false);
						
						//
						if(filter != null) {
							
							chooser.setAcceptAllFileFilterUsed(false);
							chooser.setFileFilter(filter);
						}
						
						//
						if(chooser.showOpenDialog(getComponent().getParent()) == JFileChooser.APPROVE_OPTION) {
							
							try {
								//
								openAction(chooser.getSelectedFile());
								
							}catch(final IOException ioException) {
								
								ioException.printStackTrace();
							}
						}
					}
				}).start();
			}
		});
	}
	
	/**
	 * @param file
	 * @throws IOException
	 */
	protected abstract void openAction(File file) throws IOException;
	
	/**
	 * @return the component
	 */
	public JComponent getComponent() {
	
		return component;
	}
}
